﻿using drawing_print.common;
using drawing_print.configure;
using drawing_print.util;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;
using System.Windows.Forms;

namespace drawing_print.form.custom
{    
    /// <summary>
    /// 单独处理一个图片的自定义控件
    /// </summary>
    class ImageControl : Control
    {
        /// <summary>
        /// 图片的处理流程
        /// </summary>
        public Procedures procedures = new Procedures();

        private Bitmap current_image;
        /// <summary>
        /// 放大缩小等级
        /// </summary>
        public Double zoom;
        /// <summary>
        /// 初始宽度
        /// </summary>
        public int init_width;
        /// <summary>
        /// 初始高度
        /// </summary>
        public int init_height;
        /// <summary>
        /// 截屏后的图片
        /// </summary>
        private Bitmap final_image;

        public ImageControl(Procedure procedure)
        {
            //this.BackColor = Color.Red;
            // 添加到流程中
            this.procedures.add(procedure);
            current_image = procedure.Image;
            final_image = procedure.Image;
            // 减少闪烁
            this.SetStyle(
                ControlStyles.OptimizedDoubleBuffer
                | ControlStyles.ResizeRedraw
                | ControlStyles.AllPaintingInWmPaint, true);

        }
        
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            Graphics g = e.Graphics;
            g.DrawRectangle(new Pen(Color.Green), new Rectangle(new Point(0,0), new Size(this.ClientSize.Width - 2 , this.ClientSize.Height - 2)));

            int w = this.Width, h = this.Height;
            Rectangle rect = new Rectangle(0, 0, w, h);
            g.DrawImage(current_image, rect);

            if (!this.cover)
            {
                if (current_image != null)
                {   
                    //this.BackgroundImage = current_image;
                    //this.BackgroundImageLayout = ImageLayout.Zoom;
                    //Console.WriteLine("-------刷新（全局）-------");
                }
            }
            else
            {
                
            
                // 绘制遮挡框
                g.DrawRectangle(new Pen(Color.Red) ,coverRectangle);
                //Console.WriteLine("-------刷新（截图）-------");
            }
            

        }

        /// <summary>
        /// 控件缩放
        /// </summary>
        /// <returns></returns>
        public bool deflat()
        {
            int parent_w = this.Parent.ClientSize.Width;
            int parent_h = this.Parent.ClientSize.Height;

            // 计算控件大小
            var new_width = Convert.ToInt32(this.init_width * this.zoom);
            var new_height = Convert.ToInt32(this.init_height * this.zoom);
            
            // 设置自定义控件左上角的 X,Y
            int controlsX = 0;
            int controlsY = 0;
            
            // 计算控件起点
            if (new_width <= parent_w)
            {
                controlsX = (parent_w - new_width) / 2;
            }
            if (new_height <= parent_h)
            {
                controlsY = (parent_h - new_height) / 2;
            }
            
            //设置最终值
            this.Location = new Point(controlsX, controlsY);
            this.Width = new_width;
            this.Height = new_height;

            // 刷新
            //this.Invalidate();
            this.refresh(this.procedures.last().Image);
            //Console.WriteLine("-------调整缩放比例-------");
            return true;
        }
        /// <summary>
        /// 调整角度和对比度
        /// </summary>
        /// <param name="type"></param>
        /// <param name="val"></param>
        public void drawing(string type,int val)
        {
            var first = this.procedures.first();


            // 需要操作的图片
            // Bitmap bitmap = BitmapUtil.OnlyClone(first.Image);
            Bitmap bitmap = BitmapUtil.OnlyClone(this.final_image);

            // 最后的流程
            var last = this.procedures.last();
            var angleVal = last.Angle;
            var contrastVal = last.Contrast;

           

            var new_pro = Procedure.copy(last);
            // 赋值新的值
            if ("Angle".Equals(type))
            {
                angleVal = val;
                new_pro.Type = "Angle";
                new_pro.Angle = angleVal;
            }
            if ("Contrast".Equals(type))
            {
                contrastVal = val;
                new_pro.Type = "Contrast";
                new_pro.Contrast = contrastVal;
            }
            // 调整角度
            if(first.Angle != angleVal)
            {
                bitmap = this.angle(bitmap, angleVal);
            }
            // 调整对比色
            if(first.Contrast != contrastVal)
            {
                bitmap = this.contrast(bitmap, contrastVal);
            }
            new_pro.Image = bitmap;
            
            // 添加新流程
            this.procedures.add(new_pro);
            
            // 控制缩放
            this.deflat();
        }

        /// <summary>
        /// 回退
        /// </summary>
        public Procedure fallback()
        {
            Procedure last = procedures.removeLast();
            // 刷新图片
            refresh(last.Image);
            return last;
        }
        /// <summary>
        /// 刷新图片
        /// </summary>
        private void refresh(Bitmap bitmap)
        {
            // 复制一个新的图片
            this.setImage(bitmap);
            this.Invalidate();
        }

        public Bitmap getImage()
        {
            return BitmapUtil.OnlyClone(this.current_image);
        }
        private void setImage(Bitmap image)
        {
            this.current_image = BitmapUtil.OnlyClone(image);
        }

        //---------------------------操作图片------------------------------------

        /// <summary>
        /// 调整对比度
        /// </summary>
        /// <param name="contrast">对比度的数值</param>
        public Bitmap contrast(Bitmap bitmap, int contrast)
        {

           // Bitmap img = BitmapUtil.image_duibidu(bitmap, contrast);
            Bitmap img = BitmapUtil.duibiduOnMemory(bitmap,  contrast * 10);
            // debug
            //if (ProjectConfig.debug)
            //{
            //    img.Save(ProjectConfig.contrastPath);
            //}
            return img;
        }

        /// <summary>
        /// 调整角度
        /// </summary>
        /// <param name="angle">角度</param>
        public Bitmap angle(Bitmap bitmap, int angle)
        {
            Bitmap img = BitmapUtil.RotateImage(bitmap, angle);
            // debug
            return img;
        }
        // 是否遮挡
        public Boolean cover = false;
        public Point onPoint;// 按下鼠标的位置
        public Rectangle coverRectangle;
        /// <summary>
        /// 是否
        /// </summary>
        private bool isCoverHistory = false;

        public void coverImage()
        {
   
            if (cover)
            {
                // 截屏取消
                cover = false;
                // 设置箭头光标
                this.Cursor = Cursors.Default;
            }
            else
            {
                cover = true;
                this.Cursor = Cursors.Cross;
            }
            Console.WriteLine("截屏状态(2)" + this.cover);

        }
        /// <summary>
        /// 鼠标按下
        /// </summary>
        /// <param name="e"></param>
        protected override void OnMouseDown(MouseEventArgs e)
        {
            base.OnMouseDown(e);
            if (cover)
            {
                Console.WriteLine("按下位置：" + e.Location);
                onPoint = e.Location;
                // 设置背景色
                //this.BackgroundImage = getImage();
            }
            
        }
        /// <summary>
        /// 移动鼠标  - 移动鼠标时添加边框
        /// </summary>
        /// <param name="e"></param>
        protected override void OnMouseMove(MouseEventArgs e)
        {
            base.OnMouseMove(e);
            if(cover && e.Button == MouseButtons.Left)
            {
                int w = e.Location.X - onPoint.X;
                int y = e.Location.Y - onPoint.Y;
                if (w > 0 && y > 0)
                {
                    coverRectangle = new Rectangle(onPoint, new Size(w, y));
                    this.Invalidate();
                }
            }
        }
        /// <summary>
        /// 鼠标松开
        /// </summary>
        /// <param name="e"></param>
        protected override void OnMouseUp(MouseEventArgs e)
        {
            base.OnMouseUp(e);
            if (cover)
            {
                // 截屏取消
                //cover = false;
                // 设置箭头光标
                //this.Cursor = Cursors.Default;

                var onPoint = this.onPoint;
                var offPoint = e.Location;

                if (offPoint.Equals(onPoint))
                {
                    Console.WriteLine("位置相同不处理");
                    return;
                }
                

                
                if (offPoint.X - onPoint.X <= 0 || offPoint.Y - onPoint.Y <= 0)
                {
                    Console.WriteLine("结束点不能再起点左上方。");
                    return;
                }
                // 拿到最后流程中的图片
                var last = this.procedures.last();
                var startImage = last.Image;


                double start_x = ((double)onPoint.X / this.ClientSize.Width) * startImage.Width;
                double start_y = ((double)onPoint.Y / this.ClientSize.Height) * startImage.Height;
                // 计算对应图片中的 两个点
                var start = new Point(
                    (int)start_x,
                    (int)start_y);

                var end = new Point(
                    (int)((double)offPoint.X / this.ClientSize.Width * startImage.Width),
                    (int)((double)offPoint.Y / this.ClientSize.Height * startImage.Height));


                int newWidth = end.X - start.X;
                int newHeight = end.Y - start.Y;

                Console.WriteLine(start.ToString());
                Console.WriteLine(end.ToString());

                // ---------------开始截图----------------------

                Bitmap endImage = BitmapUtil.OnlyClone(startImage);


                
                if (!util.drawing.isReverse)
                {
                    // 正选
                    Graphics gs = Graphics.FromImage(endImage);
                    
                    if (util.drawing.isMosaic)
                    {
                        // 截取的图片
                        Bitmap bufen = util.file.Mosaic.crop(endImage, new Rectangle(start.X, start.Y, newWidth, newHeight));
                        // 截取后二维码的图片
                        Bitmap newBufen = util.file.Mosaic.AdjustTobMosaic(bufen, 10);

                        gs.DrawImage(newBufen, start.X, start.Y, newWidth, newHeight);
                    }
                    else
                    {
                        gs.FillRectangle(new SolidBrush(Color.White), start.X, start.Y, newWidth, newHeight);
                    }
                    gs.Dispose();
                }
                else
                {
                    // 截取部分
                    Bitmap bufen = util.file.Mosaic.crop(endImage, new Rectangle(start.X, start.Y, newWidth, newHeight));

                    Graphics gs = null;
                    if (util.drawing.isMosaic)
                    {
                        
                        // 所有都马赛克
                        Bitmap er_quanbu = util.file.Mosaic.AdjustTobMosaic(endImage, 10);
                        gs = Graphics.FromImage(er_quanbu);

                        gs.DrawImage(bufen, start.X, start.Y, newWidth, newHeight);

                        endImage = er_quanbu;
                    }
                    else
                    {
                        
                        Bitmap bt = new Bitmap(endImage.Width, endImage.Height);
                        //Graphics _Graphics = Graphics.FromImage(bt);
                        //_Graphics.Clear(Color.White);
                        //_Graphics.Dispose();
                        gs = Graphics.FromImage(bt);
                        gs.Clear(Color.White);


                        //gs = Graphics.FromImage(bt);

                        gs.DrawImage(bufen, start.X, start.Y, newWidth, newHeight);

                        endImage = bt;
                    }
                    gs.Dispose();
                }
                

                //if (ProjectConfig.debug)
                //{
                //    endImage.Save(ProjectConfig.jietuPath);
                //}
                final_image = endImage;

                // 添加流程
                var new_procedure = Procedure.copy(last);
                new_procedure.Type = "Cover";
                new_procedure.Image = endImage;
                this.procedures.add(new_procedure);

                //this.refresh(end);
                this.deflat();
                for(int i=0; i< this.Parent.Parent.Controls[1].Controls.Count; i++)
                {
                    if(this.Parent.Parent.Controls[1].Controls[i].Name.Equals("jiaodu"))
                    {
                        this.Parent.Parent.Controls[1].Controls[i].Text = "0";
                    }
                    if (this.Parent.Parent.Controls[1].Controls[i].Name.Equals("duibidu"))
                    {
                        this.Parent.Parent.Controls[1].Controls[i].Text = "0";
                    }
                }
            }
            
        }
       
        /**
        private void mosaic()
        {
            //截取的点
            Point newP = new Point(newX, newY);
            //截取的图片
            Bitmap screenshot = ImageUtil.CutImage(image, newX, newY, newWidth, newHeight);
            screenshot.Save(@"E:\111\test\jietu222.jpg");
            // 马赛克
            Bitmap mosaic = ImageUtil.AdjustTobMosaic(screenshot, 1);
        }
        */
        public void print()
        {

           
            //PrintService ps = new PrintService();
            //ps.StartPrint(this.procedures.last().Image, "image");//打印图片 
            
            // TODO 打印。
            Console.WriteLine("-------打印成功--------");
            //打印预览
            //PrintPreviewDialog ppd = new PrintPreviewDialog();
            PrintDocument pd = new PrintDocument();
            //设置边距
            //  Margins margin = new Margins(20, 20, 20, 20);
            //  pd.DefaultPageSettings.Margins = margin;
            ////纸张设置默认
            //PaperSize pageSize = new PaperSize("First custom size", 800, 600);
            //pd.DefaultPageSettings.PaperSize = pageSize;
            //打印事件设置
            pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
            //ppd.Document = pd;
            //ppd.ShowDialog();
            try
            {
                pd.Print();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "打印出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
                pd.PrintController.OnEndPrint(pd, new PrintEventArgs());
            }
    
        }

        //打印事件处理
        private void pd_PrintPage(object sender, PrintPageEventArgs e)
        {
            System.Drawing.Image image = this.procedures.last().Image;
            int x = e.MarginBounds.X;
            int y = e.MarginBounds.Y;
            int width = image.Width;
            int height = image.Height;
            if ((width / e.MarginBounds.Width) > (height / e.MarginBounds.Height))
            {
                width = e.MarginBounds.Width;
                height = image.Height * e.MarginBounds.Width / image.Width;
            }
            else
            {
                height = e.MarginBounds.Height;
                width = image.Width * e.MarginBounds.Height / image.Height;
            }
            System.Drawing.Rectangle destRect = new System.Drawing.Rectangle(x, y, width, height);
            e.Graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, System.Drawing.GraphicsUnit.Pixel);
        }
    }
}
